import { defineStore } from "pinia";
import { GetEquipments_CameraList } from "@/data-services/api/index";
import { CameraPageVO } from "@/data-services/api/types";
import { cleanEmptyObjects } from "@/utils";

export const useCameraStore = defineStore("camera", (helpers) => {
  const { action } = helpers;

  const cameraList = ref<CameraPageVO[]>([]);
  const total = ref<number>(0);
  const loading = ref<boolean>(false);
  const cameraId = ref<string>("");
  const cameraIp = ref<string>("");

  const queryParams = reactive<{
    device_type: number;
    _id?: string;
    alias?: string;
    parent?: string;
    osdList?: any[];
  }>({
    device_type: 1, // 1 ：物理相机 4：虚拟相机
    _id: "",
    alias: "",
    parent: "",
    osdList: [],
  });

  /**
   * 查询相机列表
   */
  const getCameraList = action(async (params: Record<string, any>) => {
    loading.value = true;
    try {
      const filteredQueryParams: any = cleanEmptyObjects({
        ...params,
        condition: { ...queryParams, ...params?.condition },
        pageNumber: Math.max(0, (params?.pageNumber ?? 1) - 1),
      });
      const res = await GetEquipments_CameraList(filteredQueryParams);
      let list = res.data?.devicesList ?? [];
      list.forEach((item: any) => {
        const sortNum = item.alias && item.alias.match(/\d+/g);
        if (sortNum?.length) {
          item.sortNum = +sortNum[0];
        }
      });
      list = list.sort((a: any, b: any) => {
        return (a.sortNum || 0) - (b.sortNum || 0);
      });
      // 将该list里的数据根据alias中的数字进行排序
      cameraList.value = list;
      total.value = res.data?.totalDevices ?? 0;
      return res;
    } catch (error: any) {
      throw new Error(error.message);
    } finally {
      loading.value = false;
    }
  });
  /** 获取所有相机列表 */
  const getAllCameraList = action(async (params: Record<string, any>) => {
    loading.value = true;
    try {
      const filteredQueryParams: any = cleanEmptyObjects({
        condition: { ...queryParams, ...params?.condition },
        pageNumber: 0,
        entriesPerPage: total.value,
      });
      const res = await GetEquipments_CameraList(filteredQueryParams);
      return res.data?.devicesList ?? [];
    } catch (error: any) {
      throw new Error(error.message);
    }
  });

  return {
    cameraList,
    total,
    loading,
    cameraId,
    cameraIp,
    queryParams,
    getCameraList,
    getAllCameraList,
  };
});
